'use client';

import useDebounceFn from '@/hooks/use-debounce-fn';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { Input } from '../ui/input';
import FilterButton from './filter-button';

export default function TakeoutSearchBar({
  serverComps,
}: {
  serverComps: {
    addressSelector: React.ReactNode;
  };
}) {
  const searchParams = useSearchParams();
  const pathname = usePathname();
  const { replace } = useRouter();

  const handleSearch = useDebounceFn(
    (keywords: string) => {
      const search = new URLSearchParams(searchParams);
      keywords.length
        ? search.set('keywords', keywords)
        : search.delete('keywords');
      replace(`${pathname}?${search.toString()}`);
    },
    1000,
    [searchParams, pathname, replace],
  );

  return (
    <div className="flex items-center justify-between gap-5">
      {serverComps.addressSelector}
      <div className="relative flex items-center gap-2">
        <FilterButton />
        <Input
          className="w-64 "
          placeholder="搜索外卖"
          onChange={(e) => handleSearch(e.target.value)}
        />
        <span className=" absolute i-ri-search-line right-3 top-1/2 -translate-y-1/2" />
      </div>
    </div>
  );
}
